package com.daxt.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.config.minio.MinIoUtil;
import com.daxt.common.exception.BaseException;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.sys.InfoMapper;
import com.daxt.model.constant.BaseConstants;
import com.daxt.model.dic.AccessoryType;
import com.daxt.model.dic.SystemConfigType;
import com.daxt.model.dto.FileParam;
import com.daxt.model.service.file.Info;
import com.daxt.service.UploadService;
import com.daxt.utils.FileCopyUtil;
import com.daxt.utils.file.FileBaseUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;


@Service
public class UploadServiceImpl implements UploadService {


    @Autowired
    private MinIoUtil minIoUtil;

    @Autowired
    private InfoMapper infoMapper;


    @Override
    public String upload(FileParam fileParam) {
        //存储模式
        String accType = RedisUtil.getSysConfig(SystemConfigType.ACCESSORY_TYPE);
        if (StringUtils.isEmpty(accType)) {
            throw new BaseException(ResultCode.RESULT_ERROR.getCode(), "系统配置缺少‘ACCESSORY_TYPE’存储模式");
        }

        String filePath = "";
        try {
            String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);
            if (accType.equals(AccessoryType.TYPE_1.getKey())) {
                filePath = FileBaseUtil.uploadFile(fileParam.getBucketName(), fileParam.getFileUrl(), fileParam.getInputStream(), ossDir);
            } else if (accType.equals(AccessoryType.TYPE_2.getKey())) {

                Boolean found = minIoUtil.bucketExists(fileParam.getBucketName());
                if(!found)minIoUtil.makeBucket(fileParam.getBucketName());

                boolean boo = minIoUtil.upload(fileParam.getBucketName(), fileParam.getFileUrl(), fileParam.getInputStream());
                if (boo) {
                    filePath = fileParam.getBucketName() + "/" + fileParam.getFileUrl();
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return filePath;
    }


    @Override
    public Result<String> localUpload(String bucketName, String type, MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            int lastIndexOf = file.getOriginalFilename().lastIndexOf(".");
            String substring = file.getOriginalFilename().substring(lastIndexOf);

            String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);

            String filePath = FileCopyUtil.uploadFile(bucketName, type + "/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMM")) + "/" + UUID.randomUUID() + substring, inputStream, ossDir);
            if (!org.springframework.util.StringUtils.isEmpty(filePath)) {
                Info entity = new Info();
                entity.setBucketName(bucketName);
                entity.setFilePath(filePath);
                entity.setFileName(file.getOriginalFilename());
                entity.setCreateTime(LocalDateTime.now());
                entity.setFileType(type);
                infoMapper.insert(entity);
                return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, filePath);
//                return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, SystemConfig.showOssFile + filePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), null, null);
        }
        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), null, null);
    }


    @Override
    public Result<String> removeFile(String url) {
//        try {
//            url = new String(Base64Utils.decode(url.getBytes()), "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
//        }
//        String replace = url.replace(SystemConfig.ossIp, "");

        String replace = url;
        int indexOf = replace.indexOf("/");
        String bucketName = replace.substring(0, indexOf);
        String objectName = replace.substring(indexOf);
        boolean remove = minIoUtil.remove(objectName,bucketName);
        return ResultUtil.data(remove ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null,
                url);
    }

    @Override
    public File gainFile(String url) {

        String ossDir = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR);
        String tempPath = RedisUtil.getSysConfig(SystemConfigType.TEMP_PATH);

        //存储模式
        String accType = RedisUtil.getSysConfig(SystemConfigType.ACCESSORY_TYPE);
        if (StringUtils.isEmpty(accType)) {
            throw new BaseException(ResultCode.RESULT_ERROR.getCode(), "系统配置缺少‘ACCESSORY_TYPE’存储模式");
        }

        url = url.replace(BaseConstants.BUCKET_NAME,"");

        String extName = FileBaseUtil.getFileNameExt(url);


        File downFile = new File(tempPath + IdWorker.getIdStr() + "." + extName);
        try {
            if (accType.equals(AccessoryType.TYPE_1.getKey())) {
//                FileUtils.copyFile(new File(basePath + url), downFile);// downFile(url,);
                FileUtils.copyFile(new File(ossDir + "static/" + url), downFile);// downFile(url,);
//                FileUtils.copyFile(new File(SystemConfig.ossDir + "static/" + url.replace(basePath, "")), downFile);// downFile(url,);

            } else if (accType.equals(AccessoryType.TYPE_2.getKey())) {
                InputStream inputStream = minIoUtil.download( url, BaseConstants.BUCKET_NAME );
                if(inputStream==null){
                    return null;
                }
                FileBaseUtil.inputStreamToFile(inputStream, downFile);

            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new BaseException(ResultCode.RESULT_ERROR.getCode(), "获取文件失败");
        }

        return downFile;
    }


}
